package com.example.democlient;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKRoute;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.baidu.mapapi.RouteOverlay;
import com.example.democlient.model.Task;
import com.example.democlient.network.SocketService;
import com.example.democlient.network.serverpackets.SM_TASK_QUERY_RDFINISH_REQUEST;
import com.example.democlient.network.serverpackets.SM_TASK_QUERY_RD_REQUEST;

public class RoadDesignActivity extends MapActivity implements OnClickListener {
	private  ImageButton imgBtn;
	private  ImageButton refresh;
	private  ImageButton selfBtn;
	private ImageButton prev;
	private ImageButton next;
	private MapView mapView;  
	private MyApplication app;
    private MapController mapController;  
    private OverlayT overitem;  
    private CustomItemizedOverlay overlay ;
    private CustomItemizedOverlay overlayFinish ;
    private int onceMyPoint = 1;
    private boolean roadFlag=true;
    private int index;
    private int centerIndex=-1;
    private int size =0;
    private GeoPoint mypoint;
    private GeoPoint centerPoint;
    private final Object lock = new Object();
    
    private final Object lock1 = new Object();
    
    private LocationListener locationListener = new LocationListener() {  
    	  
        @Override  
        public void onLocationChanged(Location location) {
            if (location != null&&onceMyPoint==1) { 
            	Log.e("DDDDDDDDDDDDDDD", "DDDDDDDDDDDDDDD");
            	onceMyPoint++;
            	centerIndex=-1;
                Double geolat = location.getLatitude() * 1E6;  
                Double geoLng = location.getLongitude() * 1E6;  
                mypoint = new GeoPoint(geolat.intValue(), geoLng.intValue());  
                // 设置地图的中心   
                mapController.setCenter(mypoint);  
                mapView.getController().animateTo(mypoint);  
                app.mBMapMan.getLocationManager().removeUpdates(locationListener); 
                //new Thread(new RoadDesign(app, mypoint)).start();
                if(roadFlag&&app.roadDesignList!=null){
                	//roadDesign();
                	 new Thread(new RoadDesign(app, mypoint)).start();
                }
            }  
        }  
    };  
     
    
    private synchronized final void roadDesign(){
        Toast.makeText(RoadDesignActivity.this,"正在取得数据，请稍后..", Toast.LENGTH_SHORT).show();
        mapView.getOverlays().clear();
    	Runnable runnable = new Runnable() {
			@Override
			public void run() {
				synchronized(lock){
				for(index = 0 ; index < size; index++){
					final MKPlanNode pn = new MKPlanNode();
		        	final MKPlanNode pnNext = new MKPlanNode();
					Task task;
					Task next;
					try {
						Thread.sleep(50);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					if(index==0){
						next = app.roadDesignList.get(index);
						//next = app.getTaskByIndex(index);
						pn.pt = mypoint;
    	        		pnNext.pt = new GeoPoint((int) (next.getXaxis() * 1E6), (int) (next.getYaxis()  * 1E6));
					}else{
						task = app.roadDesignList.get(index-1);
						next = app.roadDesignList.get(index);
						//task = app.getTaskByIndex(index-1);
						//next = app.getTaskByIndex(index);
						pn.pt = new GeoPoint((int) (task.getXaxis() * 1E6), (int) (task.getYaxis()  * 1E6));
    	        		pnNext.pt = new GeoPoint((int) (next.getXaxis() * 1E6), (int) (next.getYaxis()  * 1E6));
					}
					final MKSearch myMKSearch =  new MKSearch();
					myMKSearch.init(app.mBMapMan, new MKSearchListener() {
						@Override
						public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
						}
						@Override
						public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
						}
						
						@Override
						public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
						}
						
						@Override
						public void onGetRGCShareUrlResult(String arg0, int arg1) {
						}
						
						@Override
						public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
						}
						
						@Override
						public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
							synchronized (lock) {
							      if (error != 0 || res == null){
								      Toast.makeText(RoadDesignActivity.this,"未找到成果",Toast.LENGTH_LONG).show();
								      return;
								  }
								  RouteOverlay routeOverlay = new RouteOverlay(RoadDesignActivity.this,mapView);
								  MKRoute route = res.getPlan(0).getRoute(0);
								  int distanceM = route.getDistance();
								  routeOverlay.setData(res.getPlan(0).getRoute(0));// 此处仅显现一个规划作为示例
								  app.roadDesignList.get(index).setDistanceM(distanceM);
								  System.out.println("距离:"+distanceM+"公里---节点数量:"+route.getNumSteps());
								  app.totalDistanceM += distanceM;
								  mapView.getOverlays().add(routeOverlay);//添加路线覆盖物
								  //mapView.invalidate();  //刷新地图
								  lock.notify();
								}
						}
						
						@Override
						public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
						}
						
						@Override
						public void onGetAddrResult(MKAddrInfo arg0, int arg1) {
						}
					});
		        	myMKSearch.drivingSearch("", pn, "", pnNext);
		        	Log.e("33333", "3333");
		        	try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
		        	GeoPoint point =  pnNext.pt;
		        	String tempValue = next.getId()+"#"+next.getFlag()+"#"+next.getAreaName()+"#"+next.getAddressStr()+"#"+next.getTelephone()+"#"+
		        			next.getRemark()+"#"+next.getAddressId();
		        	String title = (index+1)+"#"+(next.getFlag()==1?" 收件："+next.getAddressStr():" 派件："+next.getAddressStr());
		        	OverlayItem overlayItem = new OverlayItem(point,title , tempValue);
		        	
		        	if(next.getFinishFlag()==1){
		        		overlayFinish.addOverlay(overlayItem);
		        	}else{
		        		overlay.addOverlay(overlayItem);
		        	}
				}
				
    				if (overitem != null) {  
                        mapView.getOverlays().remove(overitem);  
                    }  
                    Drawable marker = getResources().getDrawable(R.drawable.maker1);  
                    overitem = new OverlayT(marker, mypoint,RoadDesignActivity.this,getResources());  
                    mapView.getOverlays().add(overitem);  
	        		mapView.getOverlays().add(overlay);  
	        		mapView.getOverlays().add(overlayFinish);  
	        		//new Thread(new RoadDesign(app, mypoint)).start();
				}
			}
		};
		new Thread(runnable).start();

    }
    
    private void onceStartMyLocation() {  
        app.mBMapMan.getLocationManager().enableProvider(MKLocationManager.MK_GPS_PROVIDER);  
        app.mBMapMan.getLocationManager().enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);  
        app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);  
        app.mBMapMan.getLocationManager().setNotifyInternal(5, 2);  
    }  
	Handler mainHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {
	        switch (msg.what) {  
	        	case 1:
	                size =  app.roadDesignList.size();
	                //onceStartMyLocation();//定位自己
	                onceMyPoint = 1;
	                app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);  
	                app.mBMapMan.getLocationManager().setNotifyInternal(5, 2);  
	            break;
	        	case 2:
	        		SocketService.getInstance().sendPacket(new SM_TASK_QUERY_RDFINISH_REQUEST(app.account), app);
	            break;
	        	case 3:
	        		size =  app.roadDesignList.size();
	        		roadDesign();
	            break;	
	        	case 5:
	        		roadDesign();
	        	break;
	        }  
        }
    };  
    @Override
   	public void onStart(){
   		super.onStart();
   		app = (MyApplication)this.getApplication();
   	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_road_design);
        app = (MyApplication)this.getApplication();
        app.addActivity(this);
        app.setHandler(this.getClass(),mainHandler);
        app.flag = 1;
		imgBtn = (ImageButton)findViewById(R.id.roadlistitem);
		refresh = (ImageButton)findViewById(R.id.refresh);
		selfBtn = (ImageButton)findViewById(R.id.selfPosition);
		prev =  (ImageButton)findViewById(R.id.prev);
		next =  (ImageButton)findViewById(R.id.next);
		imgBtn.setOnClickListener(this);
		refresh.setOnClickListener(this);
		prev.setOnClickListener(this);
		next.setOnClickListener(this);
		selfBtn.setOnClickListener(this);
		app.mBMapMan.start();
        // 如果使用地图SDK，请初始化地图Activity
		long iTime = System.nanoTime();
        super.initMapActivity(app.mBMapMan);
        iTime = System.nanoTime() - iTime;
        mapView = (MapView)findViewById(R.id.bmapView);

        //mapView.setTraffic(true);  
        //mapView.setStreetView(true);
        mapView.setBuiltInZoomControls(false); 
        Drawable marker = this.getResources().getDrawable(R.drawable.maker1);  
        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); 
        overlay = new CustomItemizedOverlay(marker, this); 
        
        Drawable marker1 = this.getResources().getDrawable(R.drawable.maker2);  
        marker1.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); 
        overlayFinish = new CustomItemizedOverlay(marker1, this); 
        
        mapView.getOverlays().clear();
        MyLocationOverlay mylocTest = new MyLocationOverlay(this, mapView);
        mylocTest.enableMyLocation(); // 启用定位
        mylocTest.enableCompass();    // 启用指南针
        mapView.getOverlays().add(mylocTest);
        mapController = mapView.getController();  
        // 设置地图默认的缩放级别   
        mapController.setZoom(14);
        
        centerPoint = new GeoPoint((int) (38.919341* 1E6), (int) (121.621385* 1E6)); 
        mapController.setCenter(centerPoint);  
        
        //mapView.setFocusable(true);
        //onceStartMyLocation();
        
		SocketService.getInstance().sendPacket(new SM_TASK_QUERY_RD_REQUEST(app.account), app);

    }
    public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {  
  	  
	    private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();  
	    private Context context;  
	  
	    public CustomItemizedOverlay(Drawable defaultMarker) {  
	        super(boundCenterBottom(defaultMarker));  
	    }  
	  
	    public CustomItemizedOverlay(Drawable marker, Context context) {  
	        super(boundCenterBottom(marker));  
	        this.context = context;  
	    }
	
	    @Override  
	    public int size() {  
	        return overlayItemList.size();  
	    }  
	  
	    public void clear(){
	    	overlayItemList.clear();
	    }
	    public void addOverlay(OverlayItem overlayItem) {  
	        overlayItemList.add(overlayItem);  
	        this.populate();  
	    }  
	    @Override  
	    public void draw(Canvas canvas, MapView mapView, boolean shadow) {  
	        super.draw(canvas, mapView, shadow);  
	        // Projection接口用于屏幕像素点坐标系统和地球表面经纬度点坐标系统之间的变换   
	        Projection projection = mapView.getProjection();  
	        // 遍历所有的OverlayItem   
	        for (int index = this.size() - 1; index >= 0; index--) {  
	        	System.out.println(this.size());
	            // 得到给定索引的item   
	            OverlayItem overLayItem = getItem(index);  
	            // 把经纬度变换到相对于MapView左上角的屏幕像素坐标   
	            Point point = projection.toPixels(overLayItem.getPoint(), null);  
	            Paint paintText = new Paint();  
	            paintText.setColor(Color.BLUE);
	            paintText.setTypeface(Typeface.DEFAULT_BOLD);
	            paintText.setTextSize(16);
	         //Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.bubble);
	         // canvas.drawBitmap(bmp, point.x-3 , point.y-12, paintText);
	            // 绘制文本   
	            String[] temp = overLayItem.getTitle().split("#");
	            canvas.drawText(temp[0], point.x-10, point.y-28, paintText);  
	            canvas.drawText(temp[1], point.x+15, point.y-28, paintText);  
	        }  
	
	    }
	    @Override  
	    // 处理点击事件  
	    protected boolean onTap(int i) {  
	        setFocus(overlayItemList.get(i));  
	        Toast.makeText(this.context, overlayItemList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
	        Intent toIntent = new Intent();
			toIntent.setClass(RoadDesignActivity.this,TaskQueryActivity.class);
			toIntent.putExtra("content", overlayItemList.get(i).getSnippet());
			startActivity(toIntent);
	        return true;  
	    }  
		@Override
		protected OverlayItem createItem(int i) {
			 return overlayItemList.get(i);  
		}
    }
    
	@Override
	protected void onPause() {
		if(app.mBMapMan != null )
			app.mBMapMan.stop();
		app.flag = 1;
		super.onPause();
		
	}
	@Override
	protected void onResume() {
		app.mBMapMan.start();
		if(app.flag==0){
			//this.roadDesign();
			overlayFinish.clear();
			 overlay.clear();
			 mapView.getOverlays().clear();
			 overlayFinish.clear();
			 overlay.clear();
			SocketService.getInstance().sendPacket(new SM_TASK_QUERY_RD_REQUEST(app.account), app);
		}
		if(app.flag!=0){
			app.flag = 0;
		}
		
        //app.mBMapMan.getLocationManager().removeUpdates(locationListener); 
        //app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);  
		//app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
		//SocketService.getInstance().sendPacket(new SM_TASK_QUERY_RD_REQUEST(app.account), app);
		super.onResume();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
    	super.onOptionsItemSelected(item);
    	if(item.getItemId()==R.id.menu_settings){
    		app.exit();
    	}
		return true;
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	@Override
    public void onClick(View v) {
		if(v.getId()==R.id.roadlistitem ){
			Intent toIntent = new Intent();
			toIntent.setClass(RoadDesignActivity.this,RoadDesignListActivity.class);
			startActivity(toIntent);
		}else if(v.getId()==R.id.next){
			centerIndex = centerIndex < (size-1)?centerIndex+1:(size-1);
			GeoPoint centerPoint  = new GeoPoint((int) ( app.roadDesignList.get(centerIndex).getXaxis() * 1E6), (int) ( app.roadDesignList.get(centerIndex).getYaxis() * 1E6)); 
		    mapController.setCenter(centerPoint);  
		}else if(v.getId()==R.id.prev){
			if(centerIndex<=0){
		        mapController.setCenter(mypoint);  
		        centerIndex=-1;
			}else{
				centerIndex = centerIndex>0?centerIndex-1:0;
				GeoPoint centerPoint  = new GeoPoint((int) ( app.roadDesignList.get(centerIndex).getXaxis() * 1E6), (int) ( app.roadDesignList.get(centerIndex).getYaxis() * 1E6)); 
		        mapController.setCenter(centerPoint);  
			}
		}else if(v.getId()==R.id.selfPosition){
			roadFlag=false;
			onceMyPoint=1;
			onceStartMyLocation();
		}else if(v.getId()==R.id.refresh){
			overlayFinish.clear();
			 overlay.clear();
			 mapView.getOverlays().clear();
			SocketService.getInstance().sendPacket(new SM_TASK_QUERY_RD_REQUEST(app.account), app);
		}
	}
    
}
